﻿using Common.Configurations;
using Common.Models;
using Common.Utils;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Infrastructure.Services
{
    public class TokenService : ITokenService
    {
        public string Build(IEnumerable<Claim> claims, JwtSettings options, bool isRefreshToken = false)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.SecurityKey));
            var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            DateTime expires;
            string timestamp;

            if (isRefreshToken)
            {
                expires = DateTime.Now.AddSeconds(options.RefreshExpiresSeconds);
                timestamp = expires.ToUnixTimestampSeconds().ToString();
                claims = claims.Append(new Claim(ApplicationClaimTypes.RefreshExpires, timestamp)).ToList();
            }
            else
            {
                expires = DateTime.Now.AddSeconds(options.ExpireSeconds);
                timestamp = expires.ToUnixTimestampSeconds().ToString();
                claims = claims.Append(new Claim(ApplicationClaimTypes.RefreshExpires, timestamp)).ToList();
            }

            var token = new JwtSecurityToken(
                issuer: options.Issuer,
                audience: options.Audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: expires,
                signingCredentials: signingCredentials
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        public JwtSecurityToken Decode(string jwtToken)
        {
            var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
            var jwtSecurityToken = jwtSecurityTokenHandler.ReadJwtToken(jwtToken);
            return jwtSecurityToken;
        }
    }
}
